package cn.edu.zut.curriculum.controller;

import cn.edu.zut.curriculum.entity.Commodity;
import cn.edu.zut.curriculum.entity.User;
import cn.edu.zut.curriculum.service.ICommodityService;
import cn.edu.zut.curriculum.service.impl.*;
import cn.edu.zut.curriculum.service.IUserService;
import com.sun.org.apache.xpath.internal.operations.Mod;
import lombok.experimental.Accessors;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.MissingPathVariableException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.jws.WebParam;

@Controller
public class UserController {
    @Autowired
    IUserService userService;
    @Autowired
    ICommodityService iCommodityService;
    @PostMapping("/register") //使用postmapping，管理注册页面的登陆跳转
    public ModelAndView register(User user,ModelAndView mav){
        User res = userService.register(user);
        if(res.getMessage()==null){
            mav.setViewName("/User/list");
        }
        else {
            mav.addObject("message",res.getMessage());
            mav.setViewName("User/register");
        }
        return mav;
    }
    @PostMapping("/login")
    public ModelAndView login(String account,String password,ModelAndView mav){
        System.out.println(account);
        System.out.println(password);
        User user = userService.login(account,password);
        if(user == null){
            mav.setViewName("/User/login");
            mav.addObject("message","登录失败");
        } else if (user.getRole()==1) {
            mav.addObject("administrator",user);
            mav.setViewName("/User/administratorlist");    //管理员页面
            //System.out.println(user.getEmail());
        } else {
            mav.addObject("user",user);
            mav.setViewName("/User/list");      //用户页面
            //System.out.println(user.getEmail());
        }
        return mav;
    }

    @GetMapping("/personaldata")   //个人资料更改
    public ModelAndView change(ModelAndView mav, @RequestParam("uid")long uid){
        User user=userService.select(uid);
        mav.addObject("user",user);
        mav.setViewName("/User/login");
        return mav;
    }




    //后端id还没传进去，有问题
    @PostMapping("/save")
    public ModelAndView save(User user,ModelAndView mav,@RequestParam("uid") long uid){
        user.setId(uid);
        System.out.println(user);
        int i=userService.update2(user,uid);
        if(i==1){
            mav.addObject("message","修改成功");
        }
        else
            mav.addObject("message","未知异常");
        mav.setViewName("/User/login");
        return mav;
    }



}
